import Cookies from 'js-cookie'
import { Notification, Space, Button } from '@arco-design/web-vue'
const versionKey = 'version-id'
declare global {
  interface Window {
    getVersion: (version: number) => void
  }
}

export function getVersionId() {
  return Cookies.get(versionKey) ? Number(Cookies.get(versionKey)) : 0
}

export function setVersionId(version: number) {
  return Cookies.set(versionKey, String(version))
}

export function removeVersionId(version: number) {
  Cookies.remove(versionKey)
}

export function handleVersion() {
  if (process.env.NODE_ENV !== 'development') {
    window.getVersion = (version: number) => {
      const currentVersion = getVersionId()
      // if (!currentVersion || currentVersion !== version) {
      if (currentVersion && currentVersion !== version) {
        Notification.info({
          id: 'update',
          title: '更新提示',
          content: '有新版本上传，是否立即更新',
          duration: 0,
          closable: true,
          position: 'bottomRight',
          footer: () =>
            h(Space, {}, [
              h(
                Button,
                {
                  type: 'secondary',
                  size: 'small',
                  onClick: () => Notification.remove('update')
                },
                '关闭'
              ),
              h(
                Button,
                {
                  type: 'primary',
                  size: 'small',
                  onClick: () => {
                    Notification.remove('update')
                    location.reload()
                  }
                },
                '立即更新'
              )
            ])
        })
      }
      setVersionId(version) // 保存 以便下次使用判断
    }
  }
}

export function insertVersionFile() {
  if (process.env.NODE_ENV !== 'development') {
    const scriptCollection = document.getElementsByTagName('script')
    // 判断是否已经有version.js 文件，如果有，先删掉资源引入
    const scriptAry = Array.from(scriptCollection)
    scriptAry.some((v) => {
      const flag = v.src.indexOf('version.js') !== -1
      if (flag) {
        v.parentNode?.removeChild(v)
      }
      return flag
    })

    const versionScript = document.createElement('script')
    versionScript.src = 'version.js?v=' + new Date().getTime()
    const s = document.getElementsByTagName('script')[0]
    s.parentNode?.insertBefore(versionScript, s)
  }
}
handleVersion()
